const { src, dest, parallel, series, watch } = require("gulp");
const gulp = require("gulp");

const htmlmin = require("gulp-htmlmin");

const babel = require("gulp-babel");
const terser = require("gulp-terser");

const less = require("gulp-less");

const inject = require("gulp-inject");

const browserSync = require("browser-sync");

//html打包
const htmlTask = () => {
  return src("./src/**/*.html")
    .pipe(htmlmin({ collapseWhitespace: true }))
    .pipe(dest("./dist"));
};

//js打包
const jsTask = () => {
  return src("./src/**/*.js")
    .pipe(babel({ presets: ["@babel/preset-env"] })) //转化es6==>es5
    .pipe(terser({ mangle: { toplevel: true } })) //压缩丑化
    .pipe(dest("./dist"));
};

//对less进行打包
const lessTask = () => {
  return src("./src/**/*.less").pipe(less()).pipe(dest("./dist"));
};

//在html中注入js和css
const injectTask = () => {
  return src("./dist/**/*.html")
    .pipe(inject(src(["./dist/**/*.js", "./dist/**/*.css"]), { relative: true }))
    .pipe(dest("./dist"));
};

//开启服务
const bs = browserSync.create();
const server = () => {
  watch("./src/**", buildTask);
  bs.init({
    port: 8000,
    open: true,
    files: "./dist/*",
    server: {
      baseDir: "./dist",
    },
  });
};

const buildTask = series(parallel(htmlTask, jsTask, lessTask), injectTask);

const serverTask = series(buildTask, server);

module.exports = {
  // htmlTask,
  // jsTask,
  // lessTask,
  // injectTask,
  buildTask,
  serverTask,
};
